package com.octant.testipc;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.tuya.smart.home.sdk.TuyaHomeSdk;
import com.tuya.smart.sdk.api.IDevListener;
import com.tuya.smart.sdk.api.ITuyaDevice;
import com.tuya.smart.sdk.bean.DeviceBean;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import androidx.appcompat.app.AppCompatActivity;

public class DeviceDetailActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_device_id,tv_device_name,tv_device_network,tv_device_schema,tv_device_dps;
    private ImageView iv_device_icon;
    private Button btn_preview,btn_sdcard;

    private Context mContext;
    private String devId;
    private DeviceBean deviceBean;
    private ITuyaDevice mDevice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_detail);
        mContext = DeviceDetailActivity.this;
        devId = getIntent().getStringExtra("devId");
        deviceBean = TuyaHomeSdk.getDataInstance().getDeviceBean(devId);
        mDevice = TuyaHomeSdk.newDeviceInstance(deviceBean.getDevId());
        initViews();
    }

    private void initViews() {
        tv_device_id = findViewById(R.id.tv_device_id);
        tv_device_name = findViewById(R.id.tv_device_name);
        tv_device_network = findViewById(R.id.tv_device_network);
        iv_device_icon = findViewById(R.id.iv_device_icon);
        tv_device_schema = findViewById(R.id.tv_device_schema);
        tv_device_dps = findViewById(R.id.tv_device_dps);
        btn_preview = findViewById(R.id.btn_preview);
        btn_sdcard = findViewById(R.id.btn_sdcard);

        btn_preview.setOnClickListener(this);
        btn_sdcard.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mDevice.registerDevListener(devListener);
        tv_device_id.setText(deviceBean.getDevId());
        tv_device_name.setText(deviceBean.getName());
        if (deviceBean.getIsOnline()){
            tv_device_network.setText("在线");
        }else {
            tv_device_network.setText("离线");
        }
        Glide.with(mContext).load(deviceBean.iconUrl).into(iv_device_icon);
        tv_device_schema.setText(deviceBean.getSchema());
        tv_device_dps.setText(getMapToString(deviceBean.getDps()));
    }

    @Override
    protected void onPause() {
        super.onPause();
        mDevice.unRegisterDevListener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDevice.onDestroy();
    }

    IDevListener devListener = new IDevListener() {

        /**
         * DP 数据更新
         *
         * @param devId 设备 ID
         * @param dpStr 设备发生变动的功能点，为 JSON 字符串，数据格式：{"101": true}
         */
        @Override
        public void onDpUpdate(String devId, String dpStr) {
            tv_device_dps.setText(getMapToString(deviceBean.getDps()));
        }

        /**
         * 设备移除回调

         *
         * @param devId 设备id

         */
        @Override
        public void onRemoved(String devId){
            Toast.makeText(mContext, "设备已经被移除", Toast.LENGTH_SHORT).show();
            finish();
        }

        /**
         * 设备上下线回调。如果设备断电或断网，服务端将会在3分钟后回调到此方法。

         *
         * @param devId  设备 ID
         * @param online 是否在线，在线为 true

         */
        @Override
        public void onStatusChanged(String devId, boolean online){
            if (deviceBean.getIsOnline()){
                tv_device_network.setText("在线");
            }else {
                tv_device_network.setText("离线");
            }
        }

        /**
         * 网络状态发生变动时的回调

         *
         * @param devId  设备 ID
         *  @param status 网络状态是否可用，可用为 true

         */
        @Override
        public void onNetworkStatusChanged(String devId, boolean status){
        }

        /**
         * 设备信息更新回调

         *
         * @param devId  设备 ID

         */
        @Override
        public void onDevInfoUpdate(String devId){
            tv_device_schema.setText(deviceBean.getSchema());
        }

    };


    /**
     *
     * Map转String
     * @param map
     * @return
     */
    public static String getMapToString(Map<String,Object> map){
        Set<String> keySet = map.keySet();
        //将set集合转换为数组
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        //给数组排序(升序)
        Arrays.sort(keyArray);
        //因为String拼接效率会很低的，所以转用StringBuilder
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keyArray.length; i++) {
            // 参数值为空，则不参与签名 这个方法trim()是去空格
            if ((String.valueOf(map.get(keyArray[i]))).trim().length() > 0) {
                sb.append(keyArray[i]).append(":").append(String.valueOf(map.get(keyArray[i])).trim());
            }
            if(i != keyArray.length-1){
                sb.append(",");
            }
        }
        return sb.toString();
    }

    /**
     *
     * String转map
     * @param str
     * @return
     */
    public static Map<String,Object> getStringToMap(String str){
        //根据逗号截取字符串数组
        String[] str1 = str.split(",");
        //创建Map对象
        Map<String,Object> map = new HashMap<>();
        //循环加入map集合
        for (int i = 0; i < str1.length; i++) {
            //根据":"截取字符串数组
            String[] str2 = str1[i].split(":");
            //str2[0]为KEY,str2[1]为值
            //map.put(str2[0],str2[1]);

        if (str2.length == 2){
                map.put(str2[0].trim(),str2[1]);
            }else{
                map.put(str2[0].trim(),"");
            }
        }
        return map;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_preview:{
                if (deviceBean.getIsOnline() == false){
                    Toast.makeText(mContext, "设备没有在线，无法预览", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(mContext,DeviceLiveVideoActivity.class);
                intent.putExtra("devId",devId);
                startActivity(intent);
            }break;
            case R.id.btn_sdcard:{
                if (deviceBean.getIsOnline() == false){
                    Toast.makeText(mContext, "设备没有在线", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(mContext,DeviceSdcardActivity.class);
                intent.putExtra("devId",devId);
                startActivity(intent);
            }
        }
    }
}
